/*
 * Copyright (c) 2022-2023 cetcclout Co., Ltd All rights reserved.
 * Sensor Adapter is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.cetccloud.cimp.adapter.handler.abstracts;

import cn.hutool.core.map.BiMap;

import java.nio.Buffer;
import java.util.HashMap;

import com.cetccloud.cimp.common.util.SensorStringUtils;

/**
 * @author
 * @apiNote 协议上下文到dtuid的双向转换，fromDtu、toDtu方法的第二个参数做了context <-> dtuid的转换
 * @date 2022/10/14 14:35
 */
public abstract class AbstractAuthHandler extends DtuDataHandler {
    protected BiMap<String, Object> biMap = new BiMap<>(new HashMap<>());

    /**
     * 处理来自设备的数据
     * @param context channel,通信信道标识
     */
    public void fromDtu(Buffer buffer, Object context) {
        System.out.println("AbstractAuthHandler——fromDtu");
        String dtuId = auth(buffer, context);
        // todo: 有状态、无状态的逻辑
        if(SensorStringUtils.isNotEmpty(dtuId)) {
            biMap.put(dtuId, context);
            nextFromDtuHandler.fromDtu(buffer, dtuId);
        }
        
    }

    /**
     * 处理来自设备查询返回信息
     */
    @Override
    public void fromDtuAT(Buffer buffer, Object context) {

    }

    /**
     * 处理发往设备的数据
     */
    public void toDtu(Buffer buffer, Object context) {
        Buffer out = sign(buffer, (String)context);
        nextToDtuHandler.toDtu(out, biMap.get((String)context));
    }

    /**
     * 识别设备
     */
    public abstract String auth(Buffer buffer, Object context);

    /**
     * 签名以供设备识别
     */
    public abstract Buffer sign(Buffer buffer, String dtuId);
}
